iT邦幫忙

2023 iThome 鐵人賽

DAY 18
0
Mobile Development

App從開發到上架系列 第 18

Day20: iOS 開發:畫面功能(查找附近餐廳) - CoreLocation、LocationManager

  • 分享至 

  • xImage
  •  
import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mapView.delegate = self
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let userLocation = locations.last else { return }
        
        let coordinateRegion = MKCoordinateRegion(center: userLocation.coordinate,
                                                  latitudinalMeters: 1000, longitudinalMeters: 1000)
        mapView.setRegion(coordinateRegion, animated: true)
        
        // Call function to fetch nearby restaurants using userLocation.coordinate
        fetchNearbyRestaurants(at: userLocation.coordinate)
    }
    
    func fetchNearbyRestaurants(at coordinate: CLLocationCoordinate2D) {
        let request = MKLocalSearch.Request()
        request.naturalLanguageQuery = "restaurant"
        request.region = MKCoordinateRegion(center: coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)
        
        let search = MKLocalSearch(request: request)
        search.start { (response, error) in
            guard let response = response else {
                print("Error: \(error?.localizedDescription ?? "Unknown error")")
                return
            }
            
            for item in response.mapItems {
                print("Name: \(item.name ?? "N/A"), Address: \(item.placemark.title ?? "N/A")")
                // You can add markers for each restaurant on the mapView using item.placemark.coordinate
                let annotation = MKPointAnnotation()
                annotation.coordinate = item.placemark.coordinate
                annotation.title = item.name
                annotation.subtitle = item.placemark.title
                self.mapView.addAnnotation(annotation)
            }
        }
    }
}

上一篇
Day19: iOS 開發:畫面建構(查找附近餐廳) - FindRestaurantViewController
下一篇
Day21: iOS 開發:串接API之前的準備 - NetWorkManager
系列文
App從開發到上架30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言